Imports ErrorHandling

Public Class frmMain
    'logging
    Dim WithEvents mainLog As logging = log
    Dim shouldIExit As Boolean = False
    Dim showExitMessage As Boolean = True

    Sub exitServer(Optional ByVal promptToSave As Boolean = False)
        stopServer()
        log.stopLogging()
        'sql.disconnect()

        If promptToSave Then
            Me.WindowState = FormWindowState.Normal
            Me.Show()
            Me.BringToFront()
            'If MsgBox("Do you want to save the log?", MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton1, "Save Log") = MsgBoxResult.Yes Then
            'saveLog()
            'End If
        End If

        modXML.writeConfiguration()
        iconSystray.Visible = False
        shouldIExit = True
        showExitMessage = False
        Application.Exit()
    End Sub

    Sub OnShuttingdown(ByVal sender As Object, ByVal e As Microsoft.Win32.SessionEndingEventArgs)
        exitServer()
    End Sub

    Sub OnShutdown(ByVal sender As Object, ByVal e As Microsoft.Win32.SessionEndedEventArgs)
        exitServer()
    End Sub

    Private Sub frmMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If shouldIExit Then
            If showExitMessage Then
                If MsgBox("Are you sure you wish to exit and stop the ERN server?", MsgBoxStyle.YesNo, "ERN Server") = MsgBoxResult.Yes Then
                    exitServer(True)
                Else
                    e.Cancel = True
                    shouldIExit = False
                    Me.ShowInTaskbar = False
                End If
            End If
        Else
            e.Cancel = True
            Me.ShowInTaskbar = False
            Me.Hide()
        End If
    End Sub

    Private Sub frmMain_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.GotFocus
        Me.WindowState = FormWindowState.Normal
        Me.Show()
        Me.BringToFront()
    End Sub

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not Diagnostics.Debugger.IsAttached Then
            UnhandledExceptionManager.DisplayDialog = True
            UnhandledExceptionManager.EmailScreenshot = False
            UnhandledExceptionManager.KillAppOnException = True
            UnhandledExceptionManager.ScreenshotImageFormat = Drawing.Imaging.ImageFormat.Jpeg
            UnhandledExceptionManager.SendEmail = False
            UnhandledExceptionManager.TakeScreenshot = False
            UnhandledExceptionManager.AddHandler()
        End If

        'trap logoff and shutdown events seperate from the form closing
        'so the system can shutdown
        AddHandler Microsoft.Win32.SystemEvents.SessionEnding, AddressOf OnShuttingdown
        AddHandler Microsoft.Win32.SystemEvents.SessionEnded, AddressOf OnShutdown

        ernServerVersion = Diagnostics.FileVersionInfo.GetVersionInfo(Application.ExecutablePath).FileVersion
        If ernServerVersion = "" Then ernServerVersion = "0.1.9.8.0"

        modXML.readConfiguration()

        'ensure directories for uploads exist!
        If Not IO.Directory.Exists(filesLocationAutoUpdate) Then
            IO.Directory.CreateDirectory(filesLocationAutoUpdate)
        End If
        If Not IO.Directory.Exists(filesLocationPatches) Then
            IO.Directory.CreateDirectory(filesLocationPatches)
        End If
        If Not IO.Directory.Exists(filesLocationApplications) Then
            IO.Directory.CreateDirectory(filesLocationApplications)
        End If

        sql.connect()
        CheckForIllegalCrossThreadCalls = False
        Threading.Thread.CurrentThread.Name = "MAIN"
        iconSystray.ShowBalloonTip(100, "ERN Server", "ERN is starting...", ToolTipIcon.Info)
        log.startLogging()
        startServer()
    End Sub

    Sub handleLogging(ByVal str As String) Handles mainLog.writeToLog
        txtLogging.AppendText(str)
        txtLogging.SelectionStart = txtLogging.TextLength
        txtLogging.ScrollToCaret()
    End Sub

    Private Sub ToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem1.Click
        Me.WindowState = FormWindowState.Normal
        Me.ShowInTaskbar = True
        Me.Show()
        Me.Activate()
        txtLogging.SelectionStart = txtLogging.TextLength
        txtLogging.ScrollToCaret()
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        shouldIExit = True
        Me.Close()
    End Sub

    Private Sub iconSystray_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles iconSystray.MouseDoubleClick
        Me.WindowState = FormWindowState.Normal
        Me.ShowInTaskbar = True
        Me.Show()
        Me.Activate()
        txtLogging.SelectionStart = txtLogging.TextLength
        txtLogging.ScrollToCaret()
    End Sub

    Private Sub btnStopServer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStopServer.Click
        btnStopServer.Enabled = False
        btnStartServer.Enabled = True
        stopServer()
    End Sub

    Private Sub btnStartServer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStartServer.Click
        btnStartServer.Enabled = False
        btnStopServer.Enabled = True
        startServer()
    End Sub

    Private Sub btnSaveLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveLog.Click
        saveLog()
    End Sub

    Sub saveLog()
        Dim m As String
        Dim d As String
        Dim writer As IO.StreamWriter

        If Now.Month < 10 Then m = "0" & Now.Month.ToString Else m = Now.Month.ToString
        If Now.Day < 10 Then d = "0" & Now.Day.ToString Else d = Now.Day.ToString
        dlgSaveLog.FileName = "ernLog-" & Now.Year & m & d & ".txt"
        If dlgSaveLog.ShowDialog = Windows.Forms.DialogResult.OK Then
            writer = New IO.StreamWriter(dlgSaveLog.FileNames(0), False)
            writer.AutoFlush = True
            writer.Write(txtLogging.Text)
            writer.Flush()
            writer.Close()
        End If
    End Sub

    Private Sub btnToggleLogging_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnToggleLogging.Click
        If btnToggleLogging.Text = "Hide Logging" Then
            btnToggleLogging.Text = "Show Logging"
            Me.Height = 74
        Else
            btnToggleLogging.Text = "Hide Logging"
            Me.Height = 363
        End If
    End Sub

    Private Sub txtLogging_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtLogging.TextChanged
        If txtLogging.Text.Length > 10000 Then
            txtLogging.Text.Remove(0, 1000)
        End If
    End Sub
End Class
